package mms

import grails.converters.*
 
class MobileController {


//获得所有医药零售企业
    def  listMedicineCompany =  {
        render  MedicineCompany.list() as JSON
    }

 
//获得所有餐饮企业
    def listRestaurantCompany = {
        render  RestaurantCompany.list() as JSON
    }

//    获得所有企业
//    def listCompany = {
//        render Company.list() as JSON
//    }

//获得一个医药零售企业
    def  getMedicineCompany = {
        render MedicineCompany.get(id) as JSON
    }

//获得一个餐饮企业
    def getRestaurantCompany = {
        render  RestaurantCompany.get(id) as JSON
    }



//    创建一个 InspectionLog 对象，并返回Id
    def createInspectionLog = {
        def log = new InspectionLog(params)
        if (log.save(flush:true)) {
            render log.id  as JSON
        }else {
            render("{'success':false}")
        }
        
    }


//手机上需要的接口
//0全部，1医药，2食品
//(String type)
    def listCompany = {
        if (params.type == "0") {
            //return  render(Company.list() as JSON)
            return render(contentType:"text/json") {
                array {
                    for(com in Company.findAllByGisNotEqual("") ) {
                        book(id: com.id , name: com.name , latitude: com.latitude , longitude: com.longitude )
                    }
                }	
            }
        }else if(params.type == "1"){
            //return  render(MedicineCompany.list() as JSON)

            return render(contentType:"text/json") {
                array {
                    for(com in MedicineCompany.findAllByGisNotEqual("")) {
                        book(id: com.id , name: com.name , latitude: com.latitude , longitude: com.longitude )
                    }
                }	
            }
        }else if(params.type == "2"){
           //return   render(RestaurantCompany.list() as JSON)
           return render(contentType:"text/json") {
                array {
                    for(com in RestaurantCompany.findAllByGisNotEqual("")) {
                        book(id: com.id , name: com.name , latitude: com.latitude , longitude: com.longitude )
                    }
                }	
            }
        } 
    }

 //返回公司的详细信息
 //    获得一个企业
    def  getCompany = {
        def company =  Company.get(params.companyid)  
        render(contentType:"text/json") {
            name = company.name
            id = company.id
            address = company.address
            area = company.area
            
            contact = company.contact
            latitude = company.latitude
            longitude = company.longitude
            manager = company.manager ? company.manager.toString()  : ""
            incorporator = company.incorporator ? company.incorporator.toString() : "" 
            if (company in MedicineCompany) {
                licence = company.licence
                LicenceIssue =   company.licenceIssue
                licenceExpire =  ""
            }else{
                licence =  company.sanitationLicence
                LicenceIssue =  company.sanitationLicenceIssue
                licenceExpire =  company.sanitationLicenceExpire
            }
            scopeOfBusiness =  company.scopeOfBusiness
              
        }
//"class":"mms.RestaurantCompany","id":910,"address":"北三环大明宫建材市场钢材A区西排25号","area":"100平方米","categroy":"小型餐馆","contact":"13909217722","employees":[],"gis":"910","history":[],"improper":[],"incorporator":null,"latitude":"34.321143197362666","level":"无","live":"","loginName":"sys","longitude":"108.95846876350446","manager":null,"multimedia":[],"name":"陕西麦香堡餐饮连锁有限公司","nature":"个体","password":"123","region":"","sanitationLicence":"陕餐证字(2011)第610112000680号","sanitationLicenceExpire":"2012-03-20","sanitationLicenceIssue":"2011-03-21","scopeOfBusiness":"不含生食海产品、不含裱花蛋糕","sellOfYear":""}
 
    }

    def getComplain = {
//        (String deviceId)

//        String deviceId
//        Complaints complaint
//        Date dateCreated 
        def list = []
        def complaints = Complaints.findAllByDisposeTimeIsNull()

        log.info "complaints total  : ${complaints.size()}"
        def c =   Calendar.getInstance()
 
        c.add(Calendar.HOUR , -12)

        log.info "check time : ${c.getTime().format('yyyyMMdd HH:mm')}"
        complaints.each{com ->
            def results =ComplainLog.withCriteria {
                and{ 
                    eq('complaint', com)
                    eq('deviceId', params.deviceId)
                    ge('dateCreated', c.getTime()) 
                }
                count("deviceId")
            }

             if (!results ) {
                list.add(com)
            }
        }

//   return render(contentType:"text/json") {
//                array {
//                    for(com in RestaurantCompany.findAllByGisNotEqual("")) {
//                        book(id: com.id , name: com.name , latitude: com.latitude , longitude: com.longitude )
//                    }
//                }	
//            }

        render(contentType:"text/json") {
            array {
                for(com in list) { 
                      
                    def tempcompany =  Company.get(com.companyId) 
                      
                    complaint (
                        id  : com.id , 
                        complaintTime  : com.complaintTime ,
                        complainantName  : com.complainantName ,
                        contactTel  : com.contactTel ,
                        faultType  : com.faultType ,
                        complainantContent  : com.complainantContent ,
                        companyId  : com.companyId ,
                      
                        latitude  : tempcompany?.latitude ,
                        longitude : tempcompany?.longitude ,
                      
                        companyName  : com.companyName,
                        companyAddress  : com.companyAddress ) 
                }
            }
        }
    }


    def postComplainJson = {
        def json = JSON.parse(params.json)
//        (String id, String content , String name )
        def complaint = Complaints.get(json.id)
        if (complaint) {
            complaint.disposeContent = json.content
            complaint.disposeName = json.name
            complaint.disposeTime = new Date()

            if (complaint.save(flush:true)) {
                return render("{'success':true}")
            }else{
                complaint.errors.each{
                    println it
                }
                return render("{'success':false}")
            }
        }else{
            return render("{'success':false}")
        }
    }

    def postComplain = {
//        (String id, String content , String name )
        def complaint = Complaints.get(params.long("id"))
        if (complaint) {
            complaint.disposeContent = params.content
            complaint.disposeName = params.name
            complaint.disposeTime = new Date()

            if (complaint.save(flush:true)) {
                return render("{'success':true}")
            }else{
                complaint.errors.each{
                    println it
                }
                return render("{'success':false}")
            }
        }else{
            return render("{'success':false}")
        }
    }
 
//插入记录,第一个参数是问卷的每一项记录，后面的参数是图片的字节流。
//{"id":"1","value":"小李","class":"检查人","title":"检查人","index":"a19cc895-b5c2-4485-a710-f49b17b0af8b","companyid":"3"}
//(JSONObject json,byte[] imageData)
def insertRecord = {
    def root = JSON.parse(params.json)
        log.info  root?.id  +"|"+ root?.index +"|"+ root['class']
        if (root?.id  && root?.index  && root['class']) {
            
            def ilog = InspectionLog.findByIds(root?.index)
            if (!ilog) {
                ilog = new InspectionLog(ids : root?.index)
                ilog.company = Company.get(root?.companyid)
                ilog.InspectionType = root?.type
                if (!ilog.save(flush:true)) {
                    println ilog.errors
                }
            }

            if (root['class'] == '检查人') {
                ilog.executor = root?.value
                
                ilog.save()
            }else{
                def item = new InspectionItem();
                    item.content = root?.title
                    item.result =  root?.value
                    
                    item.category =  root["class"]
            
                def f = request.getFile('imageData')
                def dest = "${servletContext.getRealPath('/')}upload/check/${new Date().format('yyyyMMddhhmm')}/${root?.index}${root?.id}.jpg"
                if(!f.empty) {
                    def dir = new File(dest.substring(0,dest.lastIndexOf("/")))
                    log.info  dest
                    log.info  dir
                    if (!dir.exists()) {
                        dir.mkdirs()
                    }
                    f.transferTo( new File(dest) )
                    //response.sendError(200,'Done'); 
                    item.multimedia  = new Multimedia( 
                        description : root?.title ,
                        path : dest , 
                        url : dest.replace(servletContext.getRealPath('/') , '/'),
                        mediaType :"picture",
                        preview : dest.replace(servletContext.getRealPath('/') , '/')
                        ).save(flush:true)
                } 
                ilog.addToItems(item)
                ilog.save()
            } 
            return render("{'success':true}")
        }
        render("{'success':false}")
}

def testLog = {
    
}

 
 
}
